<?php
require_once 'config.php';

// 检查用户是否已登录
if (!isLoggedIn()) {
    $_SESSION['flash_message'] = "请先登录后再查看个人信息";
    $_SESSION['flash_type'] = "warning";
    redirect('login.php');
}

// 获取当前用户ID
$user_id = $_SESSION['user_id'];

$errors = [];
$success = false;

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // 验证邮箱
    if (empty($email)) {
        $errors[] = "邮箱不能为空";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "邮箱格式不正确";
    } else {
        // 检查邮箱是否已被其他用户使用
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? AND user_id != ?");
        $stmt->execute([$email, $user_id]);
        if ($stmt->fetchColumn() > 0) {
            $errors[] = "该邮箱已被其他用户使用";
        }
    }
    
    // 验证姓名
    if (empty($full_name)) {
        $errors[] = "姓名不能为空";
    } elseif (strlen($full_name) > 100) {
        $errors[] = "姓名长度不能超过100个字符";
    }
    
    // 如果用户想要修改密码
    if (!empty($current_password) || !empty($new_password) || !empty($confirm_password)) {
        // 验证当前密码
        $stmt = $pdo->prepare("SELECT password FROM users WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $user_password = $stmt->fetchColumn();
        
        if (!password_verify($current_password, $user_password)) {
            $errors[] = "当前密码不正确";
        }
        
        // 验证新密码
        if (empty($new_password)) {
            $errors[] = "新密码不能为空";
        } elseif (strlen($new_password) < 6) {
            $errors[] = "新密码长度不能少于6个字符";
        } elseif ($new_password !== $confirm_password) {
            $errors[] = "两次输入的新密码不一致";
        }
    }
    
    // 如果没有错误，则更新用户信息
    if (empty($errors)) {
        try {
            // 开始事务
            $pdo->beginTransaction();
            
            // 更新基本信息
            $stmt = $pdo->prepare("UPDATE users SET email = ?, full_name = ? WHERE user_id = ?");
            $stmt->execute([$email, $full_name, $user_id]);
            
            // 如果需要更新密码
            if (!empty($new_password)) {
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE user_id = ?");
                $stmt->execute([$hashed_password, $user_id]);
            }
            
            // 提交事务
            $pdo->commit();
            
            $success = true;
            $_SESSION['flash_message'] = "个人信息更新成功";
            $_SESSION['flash_type'] = "success";
        } catch(PDOException $e) {
            // 回滚事务
            $pdo->rollBack();
            
            $errors[] = "更新失败: " . $e->getMessage();
        }
    }
}

// 获取用户信息
try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
    
    if (!$user) {
        $_SESSION['flash_message'] = "获取用户信息失败";
        $_SESSION['flash_type'] = "danger";
        redirect('index.php');
    }
    
    // 获取借阅统计
    $stmt = $pdo->prepare("SELECT 
                          COUNT(*) as total_borrowings,
                          SUM(CASE WHEN status = 'borrowed' THEN 1 ELSE 0 END) as current_borrowings,
                          SUM(CASE WHEN status = 'returned' THEN 1 ELSE 0 END) as returned_borrowings,
                          SUM(CASE WHEN status = 'borrowed' AND return_date < CURRENT_DATE() THEN 1 ELSE 0 END) as overdue_borrowings
                          FROM borrowings WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $borrowing_stats = $stmt->fetch();
} catch(PDOException $e) {
    $_SESSION['flash_message'] = "获取用户信息失败: " . $e->getMessage();
    $_SESSION['flash_type'] = "danger";
    redirect('index.php');
}

// 页面标题
$page_title = "个人信息 - 图书借阅系统";

// 引入头部
include 'header.php';
?>

<div class="row">
    <div class="col-md-4">
        <div class="card mb-4">
            <div class="card-header">
                <h4>个人资料</h4>
            </div>
            <div class="card-body">
                <h5 class="card-title"><?php echo htmlspecialchars($user['username']); ?></h5>
                <p class="card-text">
                    <strong>姓名:</strong> <?php echo htmlspecialchars($user['full_name']); ?><br>
                    <strong>邮箱:</strong> <?php echo htmlspecialchars($user['email']); ?><br>
                    <strong>注册时间:</strong> <?php echo date('Y-m-d', strtotime($user['registration_date'])); ?><br>
                    <strong>用户类型:</strong> <?php echo $user['user_type'] === 'admin' ? '管理员' : '普通用户'; ?>
                </p>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h4>借阅统计</h4>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-6 mb-3">
                        <div class="card bg-light">
                            <div class="card-body text-center">
                                <h5 class="card-title"><?php echo $borrowing_stats['total_borrowings']; ?></h5>
                                <p class="card-text">总借阅</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-6 mb-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body text-center">
                                <h5 class="card-title"><?php echo $borrowing_stats['current_borrowings']; ?></h5>
                                <p class="card-text">当前借阅</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="card bg-success text-white">
                            <div class="card-body text-center">
                                <h5 class="card-title"><?php echo $borrowing_stats['returned_borrowings']; ?></h5>
                                <p class="card-text">已归还</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="card <?php echo $borrowing_stats['overdue_borrowings'] > 0 ? 'bg-danger' : 'bg-light'; ?> <?php echo $borrowing_stats['overdue_borrowings'] > 0 ? 'text-white' : ''; ?>">
                            <div class="card-body text-center">
                                <h5 class="card-title"><?php echo $borrowing_stats['overdue_borrowings']; ?></h5>
                                <p class="card-text">逾期未还</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-3">
                    <a href="my_borrowings.php" class="btn btn-outline-primary btn-block">查看我的借阅</a>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h4>编辑个人信息</h4>
            </div>
            <div class="card-body">
                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger">
                        <ul class="mb-0">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        个人信息更新成功
                    </div>
                <?php endif; ?>
                
                <form method="post" action="">
                    <div class="form-group">
                        <label for="username">用户名</label>
                        <input type="text" class="form-control" id="username" value="<?php echo htmlspecialchars($user['username']); ?>" disabled>
                        <small class="form-text text-muted">用户名不可修改</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="email">邮箱</label>
                        <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="full_name">姓名</label>
                        <input type="text" class="form-control" id="full_name" name="full_name" value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                    </div>
                    
                    <hr>
                    <h5>修改密码</h5>
                    <p class="text-muted">如果不需要修改密码，请留空以下字段</p>
                    
                    <div class="form-group">
                        <label for="current_password">当前密码</label>
                        <input type="password" class="form-control" id="current_password" name="current_password">
                    </div>
                    
                    <div class="form-group">
                        <label for="new_password">新密码</label>
                        <input type="password" class="form-control" id="new_password" name="new_password">
                        <small class="form-text text-muted">密码长度不能少于6个字符</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm_password">确认新密码</label>
                        <input type="password" class="form-control" id="confirm_password" name="confirm_password">
                    </div>
                    
                    <button type="submit" class="btn btn-primary">保存修改</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?> 